import * as YvanUI from 'yvan-ui-wotu'
import * as debugTool from './debugTool'
import {Recommend} from "./recommend/tabs";

const React = YvanUI.React
const {render} = YvanUI.ReactDOM
const _ = YvanUI.lodash
const moment = YvanUI.moment

const ajaxInner = YvanUI.createAjax({
    // baseUrl: 'http://hysadmin.ehaoyao.com/recommend-admin',
    baseUrl: 'http://127.0.0.1:9046',
    timeout: 6000
})

const ajax = function (option): Promise<any> {
    return new Promise<any>((resolve, reject) => {
        ajaxInner(option).then(res => {
            resolve(res.rawData);

        }).catch(e => {
            YvanUI.notifyError({
                message: '网络异常',
                description: <pre>{JSON.stringify(e, null, ' ')}</pre>,
                duration: 60
            })
            reject(e)
        })
    })
};

// @ts-ignore
YvanUI.ajax = ajax;

YvanUI.extend({
    ajax,
    debugMode: true,
    serverJsUrlTransform(url: string) {
        return '/!' + url
    },
    dict: {is_enable: [{id: '-1', text: "停用"}, {id: '1', text: "启用"}]},
    formatter: {
        fmtDate(javaTimestamp: string) {
            // const moment = _.get(window, 'moment');
            if (!javaTimestamp) {
                return '';
            }
            if (typeof javaTimestamp === 'string') {
                return moment(_.toInteger(javaTimestamp)).format('YYYY-MM-DD HH:mm:ss')
            }
            var timestamp = moment(javaTimestamp);
            return timestamp.format('YYYY-MM-DD HH:mm:ss');
        },
        fmtDateNoTime(javaTimestamp: string) {
            // const moment = _.get(window, 'moment');
            if (!javaTimestamp) {
                return '';
            }
            if (typeof javaTimestamp === 'string') {
                return moment(_.toInteger(javaTimestamp)).format('YYYY-MM-DD')
            }
            var timestamp = moment(javaTimestamp);
            return timestamp.format('YYYY-MM-DD');
        }
    },
})

window['fmtDate'] = (javaTimestamp: string) => {
    if (!javaTimestamp) {
        return '';
    }
    if (typeof javaTimestamp === 'string') {
        return moment(parseInt(javaTimestamp)).format('YYYY-MM-DD HH:mm:ss')
    }
    var timestamp = moment(javaTimestamp);
    return timestamp.format('YYYY-MM-DD HH:mm:ss');
}

window['fmtDateNoTime'] = (javaTimestamp: string) => {
    if (!javaTimestamp) {
        return '';
    }
    if (typeof javaTimestamp === 'string') {
        return moment(parseInt(javaTimestamp)).format('YYYY-MM-DD')
    }
    var timestamp = moment(javaTimestamp);
    return timestamp.format('YYYY-MM-DD');
}


ajax({url: "/_yvanui/query", method: 'post-json', data:{moduleId: "o2o", db: "master", needCount: false, sqlId: "all_cats"}}).then((res)=>{
    var success = res.success;
    var msg = res.msg;
    var root = [];
    if (!success) {
        YvanUI.notifyError({
            message: '获取 cates 数据错误',
            description: <pre>{JSON.stringify(msg, null, ' ')}</pre>,
            duration: 60
        })
        return;
    }
    const temp = _.cloneDeep(res.data.data);
    var dataRes = res.data.data;
    var trav1 = {};
    //第一次扫描 建立映射关系
    _.each(dataRes, function (row) {
        trav1[_.toString(row.id)] = row;
    });

    //第二次扫描 建立父子关系
    _.each(dataRes, function (row) {
        var parent_id = row.parent_id;
        parent_id = _.toString(parent_id);
        if (parent_id === '0') {
            root.push(row);
        } else {
            if (_.has(trav1, parent_id)) {
                if (!_.has(trav1[parent_id], 'items')) {
                    trav1[parent_id].items = [];
                }
                trav1[parent_id].items.push(row);
            }
        }
    });

    //第三次扫描 建立fullName
    var collect = []
    const correlationMap = {}

    function calcFullName(parent, parentText, idArr) {
        const tArr = _.cloneDeep(idArr);
        const tp = {id: parent.id, text: parentText, idArr: tArr};
        collect.push(tp);
        _.set(correlationMap, parent.id, tp);
        _.each(parent.items, function (node) {
            const tpArr = _.cloneDeep(idArr);
            tpArr.push(node.id);
            calcFullName(node, parentText + "-" + node.text, tpArr);
        })
    }

    _.forOwn(root, function (node) {
        calcFullName(node, node.text, [node.id])
    });

    window['dict'] = {cats: root}
    window['dictMap'] = {catsMap: collect}
    window['correlationMap'] = correlationMap

}).catch((reason => {

})).finally(()=>{

})

export default function (mountTo: HTMLElement) {
    // window['debugTool'] = debugTool
    const recommend = new Recommend();
    YvanUI.jsonToRootRender(recommend).then(jsr => {
        render(
            jsr,
            mountTo
        )
    })
}
